/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.utils.HibernateUtil;
import DAO.LangueManager;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Anthares
 */
public class Language extends BaseServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     * <p/>
     * @param request  servlet request
     * @param response servlet response
     * <p/>
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException      if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String currentLocale = getLocaleString(request);
        String requestedLocale = request.getParameter("lang");
        String returnPage = request.getParameter("pagename");
        if(requestedLocale != null){
            if(!requestedLocale.equals(currentLocale)){
                if(requestedLocalExists(currentLocale, requestedLocale)){
                    HttpSession sess;
                    synchronized(sess = request.getSession()){
                        sess.setAttribute("lang", requestedLocale);
                    }
                }
            }
            dispatch(returnPage, request, response);
        } else {
            handleError(404, request, response);
        }
    }

    private boolean requestedLocalExists(String currentLocale, String requestedLocale) {
        return new LangueManager(HibernateUtil.getSessionFactory(), currentLocale).getLangueById(requestedLocale) != null;
    }
}
